package com.huiztech.kaoqinji;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.TimeZone;
import java.util.Timer;
import java.util.TimerTask;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.huiztech.kaoqinji.model.ClientDetail;

public class ClientDetailActivity extends BaseActivity {

    private TextView nameText, companyNameText, positionText, bumenText, phoneText, beizhuText, timeText;
    private ImageView imageView;
    private Button visitButton;
    private LinearLayout backLayout, beizhuLayout;
    private int customerId;
    public LocationClient mLocClient;
    public MyLocationListenner myListener = new MyLocationListenner();
    private LayoutParams params;
    private LocApplication application;
    private long recLen = 0;
    private Timer timer = new Timer();
    private TimerTask task;
    private SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
    private static final String visitTimeText = "visit_time";
    private static final String visitBtnText = "visit_btn";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_client_detail);
        findView();
        initUI();
        mLocClient = new LocationClient(this);
        mLocClient.registerLocationListener(myListener);
        setLocationOption();
        visitButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                requestLocClick();
            }
        });
        backLayout.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (visitButton.getText().toString().equals("结束")) {
                    controller.editor.putLong(visitTimeText, System.currentTimeMillis());
                    controller.editor.putString(visitBtnText, visitButton.getText().toString());
                    controller.editor.putInt("customerId", customerId);
                    controller.editor.commit();
                }
                finish();
            }
        });
        beizhuLayout.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
    }

    private void setLocationOption() {
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true);// 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setAddrType("all");
        option.setServiceName("com.baidu.location.service_v2.9");
        mLocClient.setLocOption(option);
    }

    /**
     * 手动触发一次定位请求
     */
    public void requestLocClick() {
        mLocClient.start();
        mLocClient.requestLocation();
    }

    /**
     * 定位监听函数
     */
    public class MyLocationListenner implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location == null)
                return;
            // 判断本地是否存有attendance_id字段 确定是否已经签到
            if (controller.getInfoByLocal(AppConst.SP_ATTENDANCE_KEY, null) != null) {
                // TODO 这里判断不对  应该判断是否与当前界面customer一样
                if (customerId == controller.sp.getInt(AppConst.SP_CUSTOMER_ID_KEY, -1)
                        || controller.sp.getInt(AppConst.SP_CUSTOMER_ID_KEY, -1) == -1) {
                    if (visitButton.getText().toString().equals("开始")) {
                        controller.startVisit(location.getLatitude(), location.getLongitude(), customerId);
                        task = new TimerTask() {
                            @Override
                            public void run() {
                                recLen = recLen + 1000;
                                application.setVistTime(recLen);
                                Message message = new Message();
                                message.what = 1;
                                handler.sendMessage(message);
                            }
                        };
                        timer.schedule(task, 1000, 1000);
                        visitButton.setBackgroundResource(R.drawable.visit_start);
                        visitButton.setText("结束");
                    } else {
                        controller.stopVisit(location.getLatitude(), location.getLongitude(), customerId);
                        recLen = 0;
                        application.setVistTime(recLen);
                        timeText.setText("" + formatter.format(application.getVisitTime()));
                        task.cancel();
                        visitButton.setBackgroundResource(R.drawable.visit_end);
                        visitButton.setText("开始");
                    }
                } else {
                    view.showMessage("请先结束上一次拜访!");
                }
            } else {
                view.showMessage("请先进行签到!");
            }

        }

        public void onReceivePoi(BDLocation poiLocation) {
            if (poiLocation == null) {
                return;
            }
        }

    }

    /**
     * 初始化UI
     */
    private void initUI() {
        // 设置头像图片宽高
        WindowManager wm = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
        int windowsWidth = wm.getDefaultDisplay().getWidth();
        int windowsHeight = wm.getDefaultDisplay().getHeight();
        int width = (int) (windowsWidth * 0.50); // 宽度
        int height = width;// 高度
        params = (LayoutParams) imageView.getLayoutParams();
        params.width = width;
        params.height = height;
        imageView.setLayoutParams(params);

        // 得到客户id
        @SuppressWarnings("unchecked")
        List<ClientDetail> clientDetailList = (List<ClientDetail>) model.get("clientDetail");
        int customerPosition = getIntent().getIntExtra("customerPosition", 0);
        // 设置各个组件显示内容
        customerId = clientDetailList.get(customerPosition).getId();
        nameText.setText(clientDetailList.get(customerPosition).getName());
        companyNameText.setText(clientDetailList.get(customerPosition).getCompanyName());
        positionText.setText(clientDetailList.get(customerPosition).getPosition());
        phoneText.setText(clientDetailList.get(customerPosition).getPhone());
        if (clientDetailList.get(customerPosition).equals("")) {
            imageView.setBackgroundResource(R.drawable.moren);
        } else {
            imageLoader.displayImage(AppConst.KAOQIN_UPLOAD_URL + clientDetailList.get(customerPosition).getImage(),
                    imageView, options);
        }
        formatter.setTimeZone(TimeZone.getTimeZone("GMT+00:00"));
        // 如果此次进入界面是开始拜访状态
        if (customerId == controller.sp.getInt(AppConst.SP_CUSTOMER_ID_KEY, -1)) {
            visitButton.setText(controller.sp.getString(visitBtnText, "开始"));
            if (controller.sp.getLong(visitTimeText, 0) != 0) {
                visitButton.setBackgroundResource(R.drawable.visit_start);
                recLen = System.currentTimeMillis() - controller.sp.getLong(visitTimeText, 0)
                        + application.getVisitTime();// 毫秒数
                task = new TimerTask() {
                    @Override
                    public void run() {
                        recLen = recLen + 1000;
                        application.setVistTime(recLen);
                        Message message = new Message();
                        message.what = 1;
                        handler.sendMessage(message);
                    }
                };
                timer.schedule(task, 1000, 1000);
            }
        }
    }

    private void findView() {
        application = (LocApplication) getApplication();
        visitButton = (Button) findViewById(R.id.client_detail_btn);
        nameText = (TextView) findViewById(R.id.client_detail_name);
        companyNameText = (TextView) findViewById(R.id.client_detail_company);
        positionText = (TextView) findViewById(R.id.client_detail_zhiwei);
        phoneText = (TextView) findViewById(R.id.client_detail_phone);
        imageView = (ImageView) findViewById(R.id.client_detail_image);
        backLayout = (LinearLayout) findViewById(R.id.client_detail_back_layout);
        beizhuLayout = (LinearLayout) findViewById(R.id.client_detail_addbeizhu_layout);
        timeText = (TextView) findViewById(R.id.client_detail_time_text);
    }

    // 更改UI
    final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case 1:
                timeText.setText("" + formatter.format(application.getVisitTime()));
            }
        }
    };

    // 返回键事件
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (visitButton.getText().toString().equals("结束")) {
                controller.editor.putString(visitBtnText, visitButton.getText().toString());
                controller.editor.putLong(visitTimeText, System.currentTimeMillis());
                controller.editor.putInt("customerId", customerId);
                controller.editor.commit();
            }
            finish();
            return true;
        }
        return super.onKeyDown(event.getKeyCode(), event);
    }
}
